package com.lear.njava.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lear.njava.pojo.Student;
import com.lear.njava.service.StudentService;
import com.lear.njava.util.MD5;
import com.lear.njava.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "学生控制器")
@RestController
@RequestMapping("/sms/studentController")
public class StudentController {

    @Autowired // 注入学生服务
    public StudentService studentService;

    // DELETE /sms/studentController/delStudentById
    @ApiOperation("删除或批量删除学生信息")
    @DeleteMapping("/delStudentById")
    public Result delStudentById(
            @ApiParam("要删除学生的ID列表") @RequestBody List<Integer> ids // 将待删除信息赋给ids
            ){
        // 调用服务层
        studentService.removeByIds(ids);
        return Result.ok();
    }

    // POST /sms/studentController/addOrUpdateStudent
    @ApiOperation("添加或修改学生信息")
    @PostMapping("/addOrUpdateStudent")
    public Result addOrUpdateStudent(
        @ApiParam("学生信息的JSON数据") @RequestBody Student student // 从请求中获取学生信息
    ){
        // 判断是否是添加，添加信息无id，有密码，修改有id，无密码
        Integer id = student.getId();
        if (null == id || 0 == id) {
            String password = student.getPassword(); // 获取密码
            student.setPassword(MD5.encrypt(password)); // 加密并设置密码
        }
        studentService.saveOrUpdate(student);
        return Result.ok();
    }

    // GET /sms/studentController/getStudentByOpr/1/3?name=xxx&clazzName=xxx
    @ApiOperation("分页带条件查询学生信息")
    @GetMapping("/getStudentByOpr/{pageNo}/{pageSize}")
    public Result getStudentByOpr(
            @ApiParam("分页查询的页码数") @PathVariable("pageNo") Integer pageNo,
            @ApiParam("分页查询的页大小") @PathVariable("pageSize") Integer pageSize,
            @ApiParam("查询的条件") Student student // 用Student接收查询的条件
            // @ApiParam("分页查询模糊匹配的学生姓名") String name,
            // @ApiParam("分页查询的班级名") String clazzName
    ){
        // 1.创建page对象 2.调用服务层 3.返回查询结果
        Page<Student> page = new Page<Student>(pageNo, pageSize); // mybatis-plus的Page方法
        IPage<Student> iPage = studentService.getStudentByOpr(page, student);
        return Result.ok(iPage);
    }
}
